//
//  MIDIissueController.m
//  迷笛
//
//  Created by . on 2018/9/17.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIissueController.h"
#import "CMInputView.h"

#import <QiniuSDK.h>

@interface MIDIissueController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic ,strong) UIButton *button;


@property(nonatomic,strong)UIButton * hand;

@property(nonatomic,strong)UITextView * contentText;
@property (nonatomic,strong) CMInputView *inputView;
@property(nonatomic,strong)UILabel * lable;
@property(nonatomic,strong)UIImageView * MYImage;

@property(nonatomic,strong)UIButton * backview;
@property(nonatomic,copy)NSString * releaseapi;
@property(nonatomic,copy)NSString * apptoken;
@property(nonatomic,copy)NSString * qinniuToken;
@property(nonatomic,copy)NSString *qiniuHash;
@property(nonatomic,copy)NSString * foundToken;



@end

@implementation MIDIissueController


- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    _apptoken = [user objectForKey:@"APPToken"];
    
    [self qiniuToken];
    
    
    self.view.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(Block:)];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"后退"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    

    
    
    self.inputView = [[CMInputView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 40)];
    
    self.inputView.font = [UIFont systemFontOfSize:15];
    self.inputView.placeholder = @"说点什么吧";
    self.inputView.textColor = [UIColor whiteColor];
    self.inputView.backgroundColor = [UIColor colorWithHexString:@"#1B212F"];

//    self.inputView.cornerRadius = 5;
    self.inputView.placeholderColor = [UIColor grayColor];
    //_inputView.placeholderFont = [UIFont systemFontOfSize:22];
    // 设置文本框最大行数
    [self.inputView textValueDidChanged:^(NSString *text, CGFloat textHeight)
    {
        CGRect frame = self.inputView.frame;
        frame.size.height = textHeight;
        self.inputView.frame = frame;
    }];
    
    self.inputView.maxNumberOfLines = 10;
    [self.view addSubview:self.inputView];
    
    [self HomeUI];

}
#pragma mark - 获取七牛Token

-(void)qiniuToken
{
    NSString * foundtoken = @"token";
    _foundToken = [NSString stringWithFormat:@"%@%@",MIDIApiRoot,foundtoken];
    
    [EdHttp get:_foundToken params:nil progress:^(id downloadProgress)
     {
         
     }
        success:^(id responseObject)
     {
         NSLog(@"七牛token%@",responseObject);
         self.qinniuToken = [responseObject objectForKey:@"data"];
         NSLog(@"qinniuToken---%@",self.qinniuToken);
     }
        failure:^(NSError *error)
     {
         NSLog(@"失败");
     }];
}

#pragma mark - 图片上传七牛服务器
-(void)qiniuRequest
{
    NSString *token =self.qinniuToken;
    //    NSString *tokendata =[token stringByRemovingPercentEncoding];
    
    NSString * Key = @"BTULw0loify0c2Wm6n501oiqz8XZzdiCKl05Aiab";
    //    NSString *keydata = [key stringByRemovingPercentEncoding];
    
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
//    UIImage * imgsave =self.MYImage.image;
    
//    NSString * path =NSHomeDirectory();
//    NSString * Pathimg =[path stringByAppendingString:@"/Documents/111.png"];[UIImagePNGRepresentation(imgsave) writeToFile:Pathimg atomically:YES];
//
//    NSLog(@"沙盒路径%@",path);//这是沙盒路径
    

    
//    NSString * PATH =[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),@"text"];
//    self.MYImage.image=[[UIImage alloc]initWithContentsOfFile:PATH];
    
   
    
    
    NSData *Data = UIImageJPEGRepresentation(self.MYImage.image, 1.0f);
    NSString * imagestr = [Data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //
    //    NSData *data = [imagestr dataUsingEncoding : NSUTF8StringEncoding];
    NSData *data = [imagestr dataUsingEncoding : NSUTF8StringEncoding];
    
    [upManager putData:data key:nil token:token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp)
     {
         NSLog(@"info--%@", info);
         NSLog(@"resp--%@", resp);
         NSLog(@"key--%@", Key);
         self.qiniuHash = [resp objectForKey:@"hash"];
         NSLog(@"hash值！！！！！--%@", self.qiniuHash);
         
         [self releaseRequest];
         
     }
        option:nil];
}


-(void)releaseRequest
{

    self.releaseapi = [NSString stringWithFormat:@"%@circle/dynamic/create",MIDIApiRoot];
//    [self JSONString:self.qiniuHash];
    
    NSDictionary * dic =@{@"title":self.inputView.text,@"resource":self.qiniuHash,@"circle_id":self.cirlcleID};
    
    
    [EdHttp post:self.releaseapi params:dic progress:^(id uploadProgress)
    {

    }
         success:^(id responseObject)
     {
         NSLog(@"发布成功%@",responseObject);
    }
         failure:^(NSError *error)
    {
        NSLog(@"失败");
    }];

    
}
-(void)handBtn:(UIButton * )sender
{
    
    [self qiniuRequest];
    
}





#pragma mark - 选择图片
-(void)choose
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                      {
                          //初始化UIImagePickerController
                          UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                          //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
                          //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
                          //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
                          PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                          //允许编辑，即放大裁剪
                          PickerImage.allowsEditing = YES;
                          //自代理
                          PickerImage.delegate = self;
                          //页面跳转
                          [self presentViewController:PickerImage animated:YES completion:nil];
                      }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
                      {
                          //其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
                          UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
                          //获取方式:通过相机
                          PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
                          PickerImage.allowsEditing = YES;
                          PickerImage.delegate = self;
                          [self presentViewController:PickerImage animated:YES completion:nil];
                      }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //定义一个newPhoto，用来存放我们选择的图片。
    
    UIImage * newPhoto = [info objectForKey:UIImagePickerControllerEditedImage];
    
    self.MYImage.image = newPhoto;
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 返回上一级
-(void)Block:(UIButton * )sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;//Bar的模糊效果，默认为YES

    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#171717"];
    self.title = @"乐动圈";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"],NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:WidthScale(17)]}];
    //    去掉导航黑线
    UIImage *img = [UIImage imageNamed:@""];
    [self.navigationController.navigationBar setBackgroundImage:img  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}


-(void)HomeUI
{
    [self.view addSubview:self.backview];
    [self.backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.inputView.mas_bottom).mas_offset(WidthScale(20));
        make.left.mas_offset(WidthScale(0));
        make.width.mas_offset(WidthScale(100));
        make.height.mas_offset(HeightScale(100));
    }];
    
    [self.view addSubview:self.MYImage];
    [self.MYImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.inputView.mas_bottom).mas_offset(WidthScale(20));
        make.left.mas_offset(WidthScale(0));
        make.width.mas_offset(WidthScale(100));
        make.height.mas_offset(HeightScale(100));
    }];
    
    [self.view addSubview:self.hand];
    [self.hand mas_makeConstraints:^(MASConstraintMaker *make)
    {
        make.bottom.mas_offset(kDevice_Is_iPhoneX?HeighX(-40):HeightScale(0));
            make.centerX.equalTo(self.view);
            make.width.mas_offset(self.view.frame.size.width);
            make.height.mas_offset(kDevice_Is_iPhoneX?HeighX(49):HeightScale(49));
    }];
    
    
}
-(UIButton *)backview
{
    if (!_backview)
    {
        _backview =[[UIButton alloc]init];
        [_backview setBackgroundColor:[UIColor redColor]];
        [self.backview addTarget:self action:@selector(choose) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backview;
}
//-(UILabel *)lable
//{
//    if (!_lable)
//    {
//        _lable =[[UILabel alloc]init];
//        _lable.backgroundColor =[UIColor redColor];
//    }
//    return _lable;
//}
-(UIButton *)hand
{
    if (!_hand)
    {
        _hand =[[UIButton alloc]init];
        [_hand setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
        [_hand setTitle:@"发布" forState:0];
        [_hand addTarget:self action:@selector(handBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _hand;
}
-(UIImageView *)MYImage
{
    if (!_MYImage)
    {
        _MYImage =[[UIImageView alloc]init];
    }
    return _MYImage;
}
-(NSString *)JSONString:(NSString *)aString {
    NSMutableString *s = [NSMutableString stringWithString:aString];    [s replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    [s replaceOccurrencesOfString:@"/" withString:@"\\/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    [s replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    [s replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    [s replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    [s replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    [s replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];    return [NSString stringWithString:s];
    
}

@end
